<?php

use App\Components\Admin\AuthVerification;
use App\Components\Admin\ResponseHelper;
use App\Components\Admin\Router;
use App\Components\Admin\XsrfToken;
use App\Components\Twig\TwigMiddleware;
use Slim\App;

return function (APP $app) {
    $app->get('/', 'App\Controllers\Admin\IndexController:index');

    // 管理后台路由解析
    $adminPattern = Router::getCurrentRequestControllerInfo();
    if (isset($adminPattern[2]) && !isset($adminPattern[3]) &&
        isset($_SERVER['REQUEST_METHOD'])
    ) {
        $requestMethod = strtolower($_SERVER['REQUEST_METHOD']);
        if (in_array($requestMethod, ['get', 'post', 'put', 'patch', 'delete', 'options'])) {
            $twig = ResponseHelper::createTwig();

            // 路由定义
            if ($adminPattern[0] == Router::URL_PREFIX . '/index/login') {
                // 仅入口页面使用XSRF / CSRF
                // 在业务逻辑中，仅建议交互简单的页面使用CSRF (多个提交或数据修改请求时，刷新CSRF增加了业务逻辑的复杂性)
                $app->$requestMethod($adminPattern[0], [$adminPattern[1], $adminPattern[2]])
                    ->add(TwigMiddleware::create($app, $twig))
                    ->add(new XsrfToken());
            } else {
                $app->$requestMethod($adminPattern[0], [$adminPattern[1], $adminPattern[2]])
                    ->add(TwigMiddleware::create($app, $twig))
                    ->add(new AuthVerification());
            }

            unset($twig);
        }
        unset($requestMethod);
    }
    unset($adminPattern);
};
